<?php
  include_once('utils.php');
  header('Content-type:application/json');

$modelFilter = <<< EOFilter
  <ogc:PropertyIsEqualTo>
    <ogc:PropertyName>apiso:CoverageContentTypeCode</ogc:PropertyName>
    <ogc:Literal>modelResult</ogc:Literal>
  </ogc:PropertyIsEqualTo>
EOFilter;

$observationFilter = <<< EOFilter
  <ogc:PropertyIsEqualTo>
    <ogc:PropertyName>apiso:CoverageContentTypeCode</ogc:PropertyName>
    <ogc:Literal>physicalMeasurement</ogc:Literal>
  </ogc:PropertyIsEqualTo>
EOFilter;

$wmsFilter = <<< EOFilter
  <ogc:PropertyIsEqualTo>
    <ogc:PropertyName>essi:TransferProtocol</ogc:PropertyName>
    <ogc:Literal>urn:ogc:serviceType:WebMapService:1.1.1:HTTP</ogc:Literal>
  </ogc:PropertyIsEqualTo>
EOFilter;

$sosFilter = <<< EOFilter
  <ogc:PropertyIsEqualTo>
    <ogc:PropertyName>essi:TransferProtocol</ogc:PropertyName>
    <ogc:Literal>urn:ogc:serviceType:SensorObservationService:1.0.0:HTTP</ogc:Literal>
  </ogc:PropertyIsEqualTo>
EOFilter;

$anyTextFilter = <<< EOFilter
  <ogc:PropertyIsLike wildCard="*" escape="\" singleChar="?">
    <ogc:PropertyName>AnyText</ogc:PropertyName>
    <ogc:Literal>*__TEXT__*</ogc:Literal>
  </ogc:PropertyIsLike>
EOFilter;

  $filter = '';
  if ($_REQUEST['type'] == 'cswFacet') {
    if ($_REQUEST['cswFacetModel'] == 'true' && $_REQUEST['cswFacetObservation'] == 'true') {
      $filter = "<ogc:Or>$modelFilter$observationFilter</ogc:Or>";
    }
    else if ($_REQUEST['cswFacetModel'] == 'true') {
      $filter = $modelFilter;
    }
    else if ($_REQUEST['cswFacetObservation'] == 'true') {
      $filter = $observationFilter;
    }
    else if ($_REQUEST['cswFacetWMS'] == 'true' && $_REQUEST['cswFacetSOS'] == 'true') {
      $filter = "<ogc:Or>$wmsFilter$sosFilter</ogc:Or>";
    }
    else if ($_REQUEST['cswFacetWMS'] == 'true') {
      $filter = $wmsFilter;
    }
    else if ($_REQUEST['cswFacetSOS'] == 'true') {
      $filter = $sosFilter;
    }
  }
  else if ($_REQUEST['type'] == 'cswAnyText') {
    $filter = str_replace('__TEXT__',$_REQUEST['cswAnyText'],$anyTextFilter);
  }

  $q = array();
  if ($_REQUEST['type'] == 'cswFacet' || $_REQUEST['type'] == 'cswAnyText') {
    $q = queryCatalogCSW(str_replace('__FILTER__',$filter,file_get_contents('post_template.xml')));
  }
  else if ($_REQUEST['type'] == 'openSearch') {
    $q = queryCatalogOpenSearch($_REQUEST['openSearch']);
  }

  $data = array();
  for ($i = 0; $i < count($q); $i++) {
    array_push($data,array(
       'name' => $q[$i]['title']
      ,'type' => $q[$i]['type']
      ,'svc'  => implode(', ',$q[$i]['svc'])
    ));
  }

  $names = array();
  foreach ($data as $k => $v) {
    $names[$k] = $v['name'];
  }
  array_multisort($names,SORT_ASC,$data);

  echo(json_encode(array('data' => $data)));
?>
